package com.urbanski.clipboard.client.util;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.client.action.ClientActionHandler;
import com.urbanski.clipboard.client.util.ClientConstants.ClientCommand;
import com.urbanski.clipboard.common.exception.InvalidCommandException;
import com.urbanski.clipboard.common.util.CommonConstants;
import com.urbanski.util.io.FileUtils;
import com.urbanski.util.logging.LoggingUtil;

public class ClientUtils
{
	private static final Logger LOGGER = Logger.getLogger(ClientUtils.class);
	
	private ClientUtils()
	{
	}
	
	public static void printHelp()
	{
		try
		{
			FileUtils.printFileByLine(new File(CommonConstants.HELP_FILE));
		}
		catch (IOException e)
		{
			LoggingUtil.logAndPrintError(LOGGER, "Error displaying help file (" + CommonConstants.HELP_FILE + ")", e);
		}
	}
	
	public static void printHelp(ClientCommand command)
	{
		try
		{
			FileUtils.printFileByLine(new File(CommonConstants.COMMAND_HELP_FILE_TEMPLATE.replace("$keyword", command.getKeyword())));
		}
		catch (IOException e)
		{
			LoggingUtil.logAndPrintError(LOGGER, "Error displaying help file (" + CommonConstants.HELP_FILE + ")", e);
		}
	}
	
	public static boolean processArgs(String[] args)
	{
		for (int i = 0; i < args.length; i++)
		{
			if (args[i].equals("-h") || args[i].equals("-help"))
			{
				printHelp();
			}
		}
		
		return true;
	}
	
	public static void executeCommand(String line)
	{
		String[] tokens = StringUtils.split(line);

		try
		{
			ClientCommand command = ClientCommand.getClientCommand(tokens[0]);

			ClientUtils.processCommand(command, line, tokens);
		}
		catch (InvalidCommandException e)
		{
			LoggingUtil.logAndPrintError(LOGGER, e.getMessage());
		}
		catch (Exception e)
		{
			LOGGER.error("Unexpected exception occured in command line listener", e);
		}
	}

	public static void processCommand(ClientCommand command, String line, String[] tokens)
	{
		try
		{
			ClientActionHandler actionHandler = ClientActionHandler.getActionHandler(command, tokens);

			if (!actionHandler.processHelpCommand(tokens))
			{
				actionHandler.execute();
			}
		}
		catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e)
		{
			LOGGER.error("Could not get action handler for command " + command, e);
		}
		catch (IOException e)
		{
			LoggingUtil.logAndPrintError(LOGGER, "Error sending command to server", e);
		}
	}
}
